#
# Copyright 2008 Wepoco.  http://www.wepoco.org/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from template import header, footer
from Picasa import Picasa
from mapskey import MAPS_API_KEY
from Track import putTrack, getTrack

class AlbumDisplay:
  def __init__(self):
    self.albums = []
    return
  def add(self, album):
    self.albums.append( album )
    return
  def _itemTxt(self, idx):
    return """<td><img  src="%s"/><br />
<input type="radio" name="sel_al" value="%s" onclick="confirm_al('%s')" />%s
</td>""" % (self.albums[idx].thumbnail,self.albums[idx].name,self.albums[idx].name,
self.albums[idx].title)
  def html(self):
    txt = "<table>"
    row = 0
    idx = 0
    while row < len(self.albums)/3:
      txt += "<tr>"
      for col in range(3):
        txt += self._itemTxt( idx )
        idx += 1
        pass
      txt += "</tr>"    
      row += 1
      pass
    col = 0
    txt += "<tr>"
    while col < len(self.albums)%3:
      txt += self._itemTxt( idx )
      col += 1
      idx += 1
      pass
    txt += "</tr></table>"
    return txt
  
class PhotoAlbums(webapp.RequestHandler):

  def get(self):
    self.post()

  def post(self):
    form = cgi.FieldStorage()
    act_ch = 1
    act_set = 2
    action = 0
    if form.getvalue('act_ch'):
      action = act_ch
    elif form.getvalue('sel_al'):
      action = act_set
      pass
    self.key = form.getvalue('key')
    self.track = getTrack(self.key)
    self.owner = form.getvalue('owner')
    self.album = form.getvalue('sel_al')
    if not self.owner:
      self.owner = self.track.albumOwner
      if not self.owner:
        self.owner = users.GetCurrentUser().nickname()
        pass
      pass
    self.albums = None
    try:
      urlres = urlfetch.fetch("http://picasaweb.google.com/data/feed/api/user/%s?kind=album"%self.owner)
      if urlres.status_code==200:
        self.albums = Picasa().albums(urlres.content)        
      elif urlres.status_code == 404:
        # Wrong user id perhaps?
        pass
    except:
      pass

    if action == act_set:
      self.save_change()
    elif action == act_ch:
      self.change_album()
    else:
      self.show_info()
    return

  def save_change(self):
    self.track.albumOwner = self.owner
    self.track.albumName = self.album
    self.track.timeSlip = 0
    putTrack(self.track)
    self.redirect('/photos?key=%s' % self.key)
    return

  def show_info(self):
    self.response.out.write(header(self.request))

    track_thumb_url = "http://maps.google.com/staticmap?center=%s&zoom=12&size=160x160&key=%s"%(
      self.track.geoStart, MAPS_API_KEY)
    try:
      album_thumb_url = self.albums[self.track.albumName].thumbnail
    except:
      album_thumb_url = ""

    self.response.out.write("""<form action="/photos" method="get">
<div>""")

    self.response.out.write("""<div style="float:left">
<img src="%s" width="160" height="160" alt="track" /><br/>%s
</div>""" % (track_thumb_url, self.track.name))
    if self.track.album:
      self.response.out.write("""<div><img src="%s" alt="album" /><br/>
<a target="_blank" href="http://picasaweb.google.com/%s/%s">%s</a></div>""" % (
          album_thumb_url,self.track.albumOwner,self.track.albumName,self.track.albumName))  
      pass
    self.response.out.write("""
<div>
<p>
<input type="submit" name="act_vi" value="view timeline" />
&nbsp;
<input type="submit" name="act_ch" value="choose photo album" />
</p>
</div>""")
    
    self.response.out.write("""
<input type="hidden" name="key" value="%s" />
</div></form>""" % self.key)

    # Extras - KML
    self.response.out.write("""<p><a href="/download?key=%s">Track KML</a>&nbsp;|
&nbsp;<a href="/kmllink?key=%s">Album KML</a></p>""" % (self.key,self.key))
    self.response.out.write(footer(self.request))
    return

  def change_album(self): 
    self.response.out.write(header(self.request))
    self.response.out.write("""<script type="text/javascript"> 
//<![CDATA[
function confirm_al(album_name){
  document.alform.submit();
}
//]]>
</script>
""")
    self.response.out.write("""
<form action="/photos" method="get">
<input type="hidden" name="key" value="%s" />""" % self.key)      
    self.response.out.write("""
<p><a href="http://picasaweb.google.com/">Picasa</a> albums owned by 
<input type="text" name="owner" value="%s" />
<input type="submit" name="act_ch" value="change" /></p>
</form>""" % self.owner )
    if self.albums:
      disp = AlbumDisplay()
      for name in self.albums.keys():
        disp.add( self.albums[name] )
        pass
      self.response.out.write("""
<div style="width:100%%">
<form name="alform" action="/photos" method="get">
<input type="hidden" name="key" value="%s" />""" % self.key)
      self.response.out.write(disp.html())
      self.response.out.write("""</form></div>""")
      pass
    self.response.out.write(footer(self.request))
    return
